// pages/goods_selection/goods_selection.js 
import {
    getNavigationbar,
    ReMallShopping
} from "../../api/index.js"
import {
    pinyin
} from '../../utils/pinyin';
Page({
    options: {
        styleIsolation: 'shared'
    },
    /**
     * 页面的初始数据
     */
    data: {
        navTitle: '分类',
        active: 0,
        width: 0,
        isShowMian: false,
        scrollViewHeight: 0,
        stickyTop: 0,
        isAshow: false,
        toIndex: 'A',
        intoView: "brand-section-0",
        mainList: [],
        pinyinList: [],
        indexList: ["A", "B", "C", "D", "E", "F", "G", "H","I", "J", "K", "L", "M", "N", "O","P", "Q", "R", "S", "T", "U","V","W", "X", "Y", "Z"],
        brandList: [],
        currentIndex: '',
        leftMenu: [{
                itemText: '猫用',
                itemId: 2,
                id: 2,
                type: 1,
                children: [{
                        childText: "干粮",
                        childId: 0,
                        parentId: 2,
                        "name": "干粮",
                        type: 2,
                        "id": "17",
                    },
                    {
                        childText: "湿粮",
                        childId: 1,
                        "name": "湿粮",
                        parentId: 2,
                        type: 2,
                        "id": "18",
                    },
                    {
                        childText: "零食",
                        childId: 2,
                        type: 2,
                        "name": "零食",
                        parentId: 2,
                        "id": "19",
                    }, {
                        childText: "保健品",
                        "id": "16",
                        parentId: 2,
                        type: 2,
                        "name": "保健品",
                        childId: 3,

                    }, {
                        "id": "8",
                        "name": "美容",
                        type: 2,
                        childId: 4,
                        parentId: 2,
                        childText: "美容",
                    }, {
                        "id": "5",
                        "name": "洗护",
                        childId: 5,
                        type: 2,
                        parentId: 2,
                        childText: "洗护",
                    }, {
                        "id": "7",
                        "name": "日用",
                        type: 2,
                        childId: 6,
                        parentId: 2,
                        childText: "日用",
                    }, {
                        "id": "12",
                        "name": "服饰",
                        childId: 7,
                        type: 2,
                        parentId: 2,
                        childText: "服饰",
                    }, {
                        "id": "10",
                        "name": "玩具",
                        type: 2,
                        childId: 8,
                        parentId: 2,
                        childText: "玩具",
                    }, {
                        "id": "6",
                        "name": "箱垫",
                        type: 2,
                        parentId: 2,
                        childId: 9,
                        childText: "箱垫",
                    }, {
                        "id": "21",
                        "name": "外用药",
                        parentId: 2,
                        type: 2,
                        childId: 10,
                        childText: "外用药",
                    }, {
                        "id": "25",
                        "name": "疫苗",
                        childId: 11,
                        type: 2,
                        parentId: 2,
                        childText: "疫苗",
                    }, {
                        "id": "27",
                        "name": "驱虫",
                        type: 2,
                        childId: 12,
                        parentId: 2,
                        childText: "驱虫",
                    }, {
                        "id": "-1",
                        "name": "其它",
                        type: 2,
                        parentId: 2,
                        childId: 13,
                        childText: "其它",
                    }
                ]
            },
            {
                itemText: '狗用',
                itemId: 1,
                id: 1,
                children: [{
                        childText: "干粮",
                        childId: 0,
                        parentId: 1,
                        type: 2,
                        "id": "17",
                    },
                    {
                        childText: "湿粮",
                        childId: 1,
                        parentId: 1,
                        type: 2,
                        "id": "18",
                    },
                    {
                        childText: "零食",
                        childId: 2,
                        parentId: 1,
                        type: 2,
                        "id": "19",
                    }, {
                        childText: "保健品",
                        "id": "16",
                        type: 2,
                        parentId: 1,
                        "name": "保健品",
                        childId: 3,

                    }, {
                        "id": "8",
                        "name": "美容",
                        type: 2,
                        childId: 4,
                        parentId: 1,
                        childText: "美容",
                    }, {
                        "id": "5",
                        "name": "洗护",
                        type: 2,
                        childId: 5,
                        parentId: 1,
                        childText: "洗护",
                    }, {
                        "id": "7",
                        "name": "日用",
                        childId: 6,
                        type: 2,
                        parentId: 1,
                        childText: "日用",
                    }, {
                        "id": "12",
                        "name": "服饰",
                        type: 2,
                        childId: 7,
                        parentId: 1,
                        childText: "服饰",
                    }, {
                        "id": "10",
                        "name": "玩具",
                        type: 2,
                        childId: 8,
                        parentId: 1,
                        childText: "玩具",
                    }, {
                        "id": "6",
                        "name": "箱垫",
                        parentId: 1,
                        type: 2,
                        childId: 9,
                        childText: "箱垫",
                    }, {
                        "id": "21",
                        "name": "外用药",
                        parentId: 1,
                        type: 2,
                        childId: 10,
                        childText: "外用药",
                    }, {
                        "id": "25",
                        "name": "疫苗",
                        childId: 11,
                        type: 2,
                        parentId: 1,
                        childText: "疫苗",
                    }, {
                        "id": "27",
                        "name": "驱虫",
                        childId: 12,
                        type: 2,
                        parentId: 1,
                        childText: "驱虫",
                    }, {
                        "id": "-1",
                        "name": "其它",
                        parentId: 1,
                        childId: 13,
                        type: 2,
                        childText: "其它",
                    }
                ]
            }
        ],
        classAobj: {},
        classBobj: {},
        obj: {
            childId: 0,
            childText: "干粮",
            name: '干粮',
            id: "17",
            parentId: 2,
            type: 2,
        },
        transformedData: {},
        targetId: '',
        scatid: 0, //二级分类id
        brandListLength: 0,
        itemIndex: 0, // 当前父级导航默认选中
        childIndex: 0, // 当前子级导航默认选中
        chilex: 0, // 当前子级导航默认选中
        goodsList: [],
        show: false,
        showMian: false,
        supList: [],
        params: "",
        keyword: "",
        currentPage: 1, // 当前页码
    },
    handleScrollToLower() {
        console.log('触发到底部提示打印');

        let data = {
            currentPage: this.data.currentPage++,
            counts: 10,
        }
        // this.data.supList = []
        this.getSupBrandList(data);
    },
    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        let query = wx.createSelectorQuery().in(this)
        query.select('.header').boundingClientRect()
        query.select('.van-tabs').boundingClientRect()
        query.select('.content').boundingClientRect()
        query.exec(res => {
            let headerHeight = res[0].height;
            let tabsHeight = res[1].height;
            let winWidth; // 窗口可使用宽度
            let winHeight; // 窗口可使用高度
            let tabbarHeight; // 底部导航高度
            let navTopHeight = headerHeight + tabsHeight
            const systemInfo = wx.getSystemInfoSync();

            // 滚动区域高度
            that.setData({
                width: systemInfo.windowWidth - 120,
                scrollViewHeight: res[2].height - 44,
                stickyTop: navTopHeight,
                isAshow: true
            })
        })
    },




    fn(str) {

        //获取全写拼音（调用js中方法）        
        console.log(pinyin)
        var fullName = pinyin.getFullChars(str);

        //获取简写拼音（调用js中方法）

        var easyName = pinyin.getCamelChars(str);

        console.log(str) //急急如意令

        console.log(fullName); //JiJiRuYiLing

        console.log(easyName); //JJRYL

    },

    /**
     * 品牌列表
     */
    getBrand() {
        getNavigationbar({
            act: 'brand_list',
            // keyword: this.data.keyword,
            p: 1,
            rollpage: 1000000,
        }).then(res => {
            console.log('分类', res)
            const arr = res.map(item => {
                return {
                    ...item,
                    pinyin: this.getPinyinFirst(item.name)
                }
            })

            const groupedByPinyin = arr.reduce((acc, obj) => {
                const key = obj.pinyin;
                if (!acc[key]) {
                    acc[key] = [];
                }
                acc[key].push(obj);
                return acc;
            }, {});
            let result = []
            Object.keys(groupedByPinyin)
                .sort()
                .forEach((key, index) => {
                    result.push({
                        index: index,
                        indexName: key.toUpperCase(),
                        list: groupedByPinyin[key]
                    });
                });
            this.setData({
                brandList: result
            })
        })

    },

    /**
     * 根据拼音首字母分组
     * @param {*} list
     */
    getListByGroup(list) {
        const map = new Map()
        list.forEach((item, index, arr) => {
            if (!map.has(item.indexName)) {
                map.set(
                    item.indexName,
                    arr.filter(a => a.indexName == item.indexName)
                )
            }
        })
        return Array.from(map).map(item => [...item[1]])
    },
    /**
     * tabs标签选中回调函数方法
     * @param {*} e 
     */
    handleTabsChange(e) {
        this.setData({
            active: e.detail.index
        })
        this.data.supList = []
        this.data.currentPage = 1
        wx.nextTick(() => {
            if (e.detail.index == 1) {
                let itemData = {
                    id: 2,
                    name: "猫用",
                    parentId: 2,
                    numId: 2,
                    type: 1,
                }
                this.data.classAobj.value = {
                    ...itemData
                }
                this.data.classBobj.value = this.data.obj
                this.data.itemIndex = 1
                this.data.leftMenu[0].itemId = 1
                let indexs = this.data.leftMenu[0].itemId
                this.setData({
                    itemIndex: 2,
                    indexs: 2,
                    childIndex: 0,
                    chilex: 0
                })
                this.getGoodsList(itemData)
            } else if (e.detail.index == 0) {
                this.getBrand()
            } else {
                this.getSupBrandList()
            }
        })
        this.setData({
            isAshow: true
        })
    },
    /**
     * 子级分类点击
     * @param {*} event  
     */
    hanclassification(event) {
        console.log('点击', event, '父id', this.data.itemIndex)
        let pettypeid = ''
        if (this.data.itemIndex == 1) {
            pettypeid = 2
        } else if (this.data.itemIndex == 2) {
            pettypeid = 1
        }
        if (this.data.classAobj.value.name == '猫用') {
            this.data.classAobj.value = {
                ...this.data.classAobj.value,
                numId: 2
            }
        } else if (this.data.classAobj.value == '狗用') {
            this.data.classAobj.value.name = {
                ...this.data.classAobj.value,
                numId: 1
            }
        }

        let obj = {
            ...event.currentTarget.dataset.value,
            scatid: this.data.scatid,
            pettype: this.data.classAobj.value.parentId,
            bcatids: this.data.itemIndex,
            classBname: {
                ...this.data.classBobj.value
            },
            classAname: {
                ...this.data.classAobj.value
            },
            shipping: false,
            url: 'goods_selection'
        }
        let objStr = encodeURIComponent(JSON.stringify(obj));
        wx.navigateTo({
            url: '/pages/goods_list/index?obj=' + objStr,
        })

    },
    /**
     * 下滑触发
     * @param {*} event 
     */
    handlePageScroll(event) {
        let that = this;
        // 初始化获取每一个indexBar的 top 和 bottom
        this.getMainItemHandler();
        // 当前高度为 所滑动top + 距顶部距离
        let nowTop = event.detail.scrollTop + this.data.stickyTop;
        this.data.mainList.forEach((item, index) => {
            // 判断区间List是否完全取出
            if (that.data.mainList[index + 1]) {
                if (nowTop >= item.top & nowTop < that.data.mainList[index + 1].top) {
                    that.setData({
                        toIndex: that.data.brandList[index].indexName
                    })
                    return
                }
            } else {
                if (nowTop >= item.top) {
                    that.setData({
                        toIndex: that.data.brandList[index].indexName
                    })
                    return
                }
            }
        })
    },

    /**
     * 初始化获取每一个index-bar的位置
     */
    getMainItemHandler() {
        if (this.isFirstScroll) {
            return; // 如果已经是第一次滚动，则直接返回，避免重复计算位置信息
        }

        let mainList = [];
        this.data.brandList.forEach((item) => {
            mainList.push({});
        });

        let count = 0; // 用于记录已经执行完的查询数量
        mainList.forEach((item, index) => {
            wx.createSelectorQuery()
                .select(`#section-${index}`)
                .boundingClientRect((rect) => {
                    if (rect) {
                        mainList[index].top = rect.top;
                        mainList[index].bottom = rect.bottom;

                        count++;
                        if (count === mainList.length) {
                            // 当所有节点位置信息都查询完毕后，更新数据并设置 isFirstScroll 为 true
                            this.setData({
                                mainList: mainList
                            });
                            this.isFirstScroll = true;
                        }
                    } else {
                        // console.log(`未找到元素 #section-${index}`);
                    }
                })
                .exec();
        });
    },

    /**
     * 索引栏字母点击
     * @param {*} event 
     */
    letterClick: function (e) {
        var index = e.currentTarget.dataset.index ; // 获取点击的字母索引值
        var letter = this.data.indexList[index]; // 获取对应索引值的字母
        console.log('点击的字母为：', letter);
        // 调试语句，查看item数组内容
        console.log('this.data.brandList', this.data.brandList)
        var targetItem = this.data.brandList.find(item => item.indexName === letter); // 找到对应字母位置的item
        var indexxx = this.data.brandList.findIndex(item => item.indexName === letter);
        if (targetItem && indexxx !== -1) {
            // if (targetItem[0].index) {
            let targetViewId = "brand-section-" + indexxx ; // 构造目标位置的id
            console.log('targetViewId', targetViewId)
            this.setData({
                intoView: targetViewId, // 更新intoView值
                currentIndex: indexxx + 1
            });

            setTimeout(() => {
                this.setData({
                    currentIndex: ''
                })
            }, 2000);
            // } else {
            //     console.log('未找到对应位置的item或index未定义');
            // }
        } else {
            console.log('未找到对应位置的item');
        }
    },

    /**
     * 跳转
     * @param {*} event 
     */
    brandClick(event) {
        console.log('e', event)
        const {
            value
        } = event.currentTarget.dataset
        value.brandid = value.id
        wx.navigateTo({
            url: `/pages/brand_list/index?data=${JSON.stringify(value)}`,
        })
    },
    /**
     * 跳转
     * @param {*} event 
     */
    enter(event) {
        console.log('e', event)
        let obj
        if(event.currentTarget.dataset.value.agentid == null && event.currentTarget.dataset.value.agentid == undefined) {
             obj = {
                ...event.currentTarget.dataset.value,
                name: event.currentTarget.dataset.value.brand_name,
                show: true,
                RefundStatus: [],
                url: 'goods_selection',
                agent_name: event.currentTarget.dataset.agent_name,
                agent_thumb:  event.currentTarget.dataset.agent_thumb,
                agentid:event.currentTarget.dataset.agentid
            }
        } else {
             obj = {
                ...event.currentTarget.dataset.value,
                name: event.currentTarget.dataset.value.brand_name,
                show: true,
                RefundStatus: [],
                url: 'goods_selection',
                
            }
        }
       
        let objStr = encodeURIComponent(JSON.stringify(obj));
        wx.navigateTo({
            url: '/pages/brand_detail/index?obj=' + objStr,
        })
    },
    /**
     * 分类左侧父级菜单导航点击回调事件方法
     * @param {*} e 
     */
    handleItmeChange(e) {

        let itemData = e.currentTarget.dataset
        let itemIndex = itemData.id
        let childIndex = this.data.childIndex

        // 判断当前点击的父级菜单是否已展开
        if (itemIndex === this.data.itemIndex) {
            // 如果已展开，则收缩隐藏
            childIndex = childIndex === 0 ? -1 : 0
        } else {
            // 如果未展开，则展开
            childIndex = 0
        }

        this.setData({
            itemIndex: itemIndex,
            childIndex: childIndex,
            chilex: 0
        })
        console.log('1', this.data.childIndex)
        // 根据点击的父级菜单项获取对应的商品列表
        this.getGoodsList(itemData)
    },
    handleItemChange(e) {
        console.log('12', this.data.childIndex)
        const itemId = e.currentTarget.dataset.id;

        // if (this.data.childIndex === itemId) {
        //     this.setData({
        //         itemIndex: itemId,
        //         childIndex: -1, // 点击已展开的菜单项，收起子菜单
        //     });
        // } else {
        //     this.setData({
        //         itemIndex: itemId,
        //         childIndex: itemId, // 点击未展开的菜单项，展开对应子菜单
        //     });
        // }
        this.getGoodsList(itemId)
    },
    /**
     * 分类左侧子级菜单导航点击回调事件方法
     * @param {*} e 
     */
    handleChildChange(e) {
        console.log('子级', e)
        let childData = e.currentTarget.dataset;
        this.data.classBobj.value = {
            ...childData.value
        }
        this.setData({
            chilex: childData.id
        })
        this.getGoodsList(childData.value)
    },

    /**
     * 获取右侧商品列表内容
     */
    getGoodsList(item) {
        console.log('item', item)
        if (item.id == 2) {
            item.parentId = 2
            item.id = 17
            this.data.classAobj.value = {
                numId: 2,
                parentId: 2,
                id: 2,
                name: "猫用",
                type: 1
            }
        } else if (item.id == 1) {
            item.parentId = 1
            item.id = 17
            this.data.classAobj.value = {
                numId: 1,
                parentId: 1,
                id: 1,
                name: "狗用",
                type: 2
            }
        }
        this.data.scatid = item.id
        getNavigationbar({
            act: 'catetory_list',
            pettype: item.parentId,
            scatid: item.id,

        }).then(res => {
            console.log('分类数据列表', res)
            wx.nextTick(() => {
                res.forEach(element => {
                    Object.assign(element, {
                        goodsImg: 'https://static.chonglaoban.cn' + element.logo,
                        goodsName: element.name,
                        type: 3,
                    })
                });
                this.setData({
                    goodsList: res
                })
            })
        })
    },

    /**
     * 获取供应商品牌列表
     */
    getSupBrandList() {
        ReMallShopping({
            act: 'supplier_list',
            p: this.data.currentPage
        }).then(res => {
            console.log('获取供应商品牌列表', res)
            wx.nextTick(() => {

                res.forEach(element => {

                    if (element.brand_list.length != 0) {
                        element.brand_list.forEach(elements => {
                            Object.assign(elements, {
                                name: element.agent_name,
                                type: 3,
                                agent_name: element.agent_name,
                                agent_thumb: element.agent_thumb,
                            })
                        });
                    } else {
                        element.product_list.forEach(elements => {

                            Object.assign(elements, {
                                name: elements.agent_name,
                                type: 3,
                                agent_name: elements.agent_name,
                                agent_thumb: elements.agent_thumb,
                            })
                        });

                    }
                });
                const arr = res.map(item => {
                    return {
                        ...item,
                        brand_list: item.brand_list.length ? item.brand_list : item.product_list
                    }
                })
                arr.forEach(element => {
                    console.log('element.brand_list.length > 0 && element.product_list > 0', element.brand_list.length > 0 && element.product_list.length > 0)
                    if (element.brand_list.length > 0 && element.product_list.length > 0) {

                        Object.assign(element, {
                            show: true
                        })
                    } else {
                        Object.assign(element, {
                            show: false,
                        })
                    }
                });

                console.log('supList', this.data.supList, arr)
                wx.nextTick(() => {
                    // 更新页面数据
                    this.setData({
                        isShowMian: true,
                        supList: this.data.supList.concat(arr), // 将新数据追加到原有数据后面

                    }, () => {
                        this.computeScrollViewHeight()
                    })
                })

            })
        })
    },
    /**
     * 获取拼音首字
     */
    getPinyinFirst(name) {
        const firstChar = name.charAt(0); // 获取字符串的第一个字
        // 将第一个字转换为拼音
        const pinyinResult = pinyin(firstChar, {
            pattern: 'first',
            toneType: 'none',
            type: 'array'
        });
        console.log(pinyinResult, 'pinyinResult')
        const pinyinInitial = pinyinResult[0].toUpperCase(); // 获取首字母并转为大写
        // console.log(pinyinInitial,'sdd----')
        //   let result = china.getSpell(name);
        //   if (china.getSpell(name).startsWith('[')) {
        //     result = china.getSpell(name).substring(1,2)
        //   }
        return pinyinInitial;
    },
    pinyinSort(name) {
        //name数组
        var pinyinArray = new Array();
        let data = []
        for (var bukn = 0; bukn < name.length; bukn++) {
            var o = new Object();
            var ken = china.getSpell(name[bukn], function (charactor, spell) {
                // console.log('charactor', charactor, spell);
                var pinyin = spell;
                spell.forEach(element => {
                    data.push(element)
                });
            });
            o.name = name[bukn];
            pinyinArray.push(o);
        }
        pinyinArray.forEach((element, index) => {
            Object.assign(element, {
                pinyin: data[index]
            })
        });
        console.log('pinyinArray');
        console.log(pinyinArray);
        // pinyinArray = pinyinArray.sort(compare("pinyin"))
        let map = {
            // 字段根据你用的组件名字进行更改
            letter: '',
            data: [],
        };
        pinyinArray.forEach((item, index) => {
            if (!map[item.pinyin[0].toUpperCase()]) {
                map[item.pinyin[0].toUpperCase()] = {
                    letter: item.pinyin[0].toUpperCase(),
                    data: [],
                };
            }
            // map[item.pinyin[0].toUpperCase()].datas.push({
            //   name: item.name,
            //   pinyin: item.pinyin,
            // });
            // console.log('item.pinyin[0].toUpperCase()', item.pinyin[0].toUpperCase())
            this.data.pinyinList.push(item.pinyin[0].toUpperCase())
            map[item.pinyin[0].toUpperCase()].data.push(item.name);
        });

        var turn = new Array();
        var letters = '*ABCDEFGHIJKLNMOPQRSTUVWXYZ'.split('');
        for (var i = 1; i < letters.length; i++) {
            if (map[letters[i]]) {
                var obj = new Object();
                //自己改改命名改成自己需要的组件名字我用的uni-index-list
                obj.letter = letters[i];
                obj.data = map[letters[i]].data;
                turn.push(obj);
            }
        }

        return turn;
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        console.log("params", this.data.params)
        if (this.data.params) {
            let objStr = decodeURIComponent(this.data.params);
            let obj = JSON.parse(objStr);
            let keyword = obj.keyword
            this.setData({
                keyword: keyword
            })
        }
        this.getSupBrandList()
        this.getBrand();

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})